package com.jgybzx.my_time_at_portia.service.base.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jgybzx.my_time_at_portia.entity.base.Item;
import com.jgybzx.my_time_at_portia.entity.base.ItemDependency;
import com.jgybzx.my_time_at_portia.mapper.base.ItemDependencyMapper;
import com.jgybzx.my_time_at_portia.mapper.base.ItemMapper;
import com.jgybzx.my_time_at_portia.service.base.ItemService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ItemServiceImpl extends ServiceImpl<ItemMapper, Item>
        implements ItemService {

    //    @Autowired
    private ItemMapper itemMapper;
    private ItemDependencyMapper itemDependencyMapper;
    private Map<String, Integer> totalMaterials = new HashMap<>();


    public ItemServiceImpl(ItemMapper itemMapper, ItemDependencyMapper itemDependencyMapper) {
        this.itemMapper = itemMapper;
        this.itemDependencyMapper = itemDependencyMapper;
    }

    @Override
    public String test(String test) {
        return itemMapper.test(test);
    }

    @Override
    public String getInfo(String test) {
        List<Item> info = itemMapper.getInfo(test);
        return info.toString();
    }

    @Override
    public String importData(MultipartFile upLoad) throws IOException {
        itemMapper.truncateItemsTable();
        itemMapper.truncateItemDependenciesTable();
        itemMapper.truncateErrorLogTable();
        List<Item> list = EasyExcel.read(upLoad.getInputStream()).head(Item.class).sheet().doReadSync();
        for (Item item : list) {
            itemMapper.insert(item);
        }
        for (Item item : list) {
//            if (!Objects.equals(item.getItemName(), "强化青铜剑")) {
//                continue;
//            }
            String remark = item.getRemark();
            String itemName = item.getItemName();
            Integer itemId = item.getItemId();
            Map<String, String> map = splitStringByNewLine(item);
            if (map.isEmpty()) {
                continue;
            }

            // 构建 itemDependencies
            for (Map.Entry<String, String> stringStringEntry : map.entrySet()) {
                String dependency_name = stringStringEntry.getKey();
                List<Item> infoByItemName = itemMapper.getInfoByItemName(dependency_name);
                if (infoByItemName.isEmpty()) {
                    itemMapper.errorLog(itemId, itemName, "没有找到材料;" + dependency_name, new Date());
                } else {
                    for (Item Item : infoByItemName) {
                        String quantity = stringStringEntry.getValue();
                        ItemDependency itemDependency = new ItemDependency();
                        // 合成物数据
                        itemDependency.setItemId(itemId);
                        itemDependency.setItemName(itemName);
                        // 材料数据
                        itemDependency.setDependencyId(Item.getItemId());
                        itemDependency.setDependencyName(dependency_name);
                        itemDependency.setQuantity(Integer.parseInt(quantity));
                        itemDependencyMapper.insert(itemDependency);
                    }

                }

            }

        }
        return "";
    }

    @Override
    public Map<String, Object> getRequiredMaterials(String itemName, int quantity) {
        // 清空总数量累积
        totalMaterials.clear();
        Map<String, Object> result = new HashMap<>();
        int itemId = itemMapper.getInfoByItemName(itemName).get(0).getItemId();
        calculateMaterials(itemId, quantity, result);
        result.put("总数", totalMaterials);
        return result;
    }

    @Override
    public List<String> item() {
        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("item_type", "原材料");

        List<Item> items = itemMapper.selectList(queryWrapper);
        return items.stream().map(Item::getItemName).collect(Collectors.toList());
    }

    public Map<String, String> splitStringByNewLine(Item item) {
        String remark = item.getRemark();
        String patentItemName = item.getItemName();
        Integer patentItemId = item.getItemId();
        Map<String, String> map = new LinkedHashMap<>();
        if (remark == null || remark.isEmpty()) {
            itemMapper.updateById(item);
            return map;
        }
        String[] lines = remark.split("\\r?\\n");
        for (int i = 0; i < lines.length; i++) {
            // 奇数行（0-based index）
            if (i % 2 == 0) {
                String key = lines[i];
                // 确保有偶数行
                if (i + 1 < lines.length) {
                    // 偶数行，取“/”后的数据
                    // 对于偶数位的数据（奇数索引），保留“/”之后的数字
                    String[] parts = lines[i + 1].split("/");
                    if (parts.length > 1) {
                        String value = parts[parts.length - 1];
                        map.put(key, value);
                    } else {
                        // 如果没有“/”，记录错误信息
                        itemMapper.errorLog(patentItemId, patentItemName, "没有'/';" + Arrays.toString(lines), new Date());
                    }
                } else {
                    // 如果 没有偶数行 记录错误数据
                    itemMapper.errorLog(patentItemId, patentItemName, "没有偶数行;" + Arrays.toString(lines), new Date());
                }
            }
        }
        item.setSynthesisFormula(JSON.toJSONString(map));
        itemMapper.updateById(item);
        return map;
    }


    private void calculateMaterials(int itemId, int quantity, Map<String, Object> result) {
        List<ItemDependency> dependencies = itemMapper.getItemDependencies(itemId);

        if (dependencies.isEmpty()) {
            // 如果没有依赖，说明是基本物品，直接累加数量
            Item item = itemMapper.getItemById(itemId);
            totalMaterials.put(item.getItemName(), totalMaterials.getOrDefault(item.getItemName(), 0) + quantity);
            return;
        }

        // 获取当前物品信息
        Item item = itemMapper.getItemById(itemId);
        Map<String, Object> itemData = new HashMap<>();
        itemData.put("quantity", quantity);

        List<Map<String, Object>> materials = new ArrayList<>();

        // 遍历所有依赖的物品
        for (ItemDependency dependency : dependencies) {
            int dependencyId = dependency.getDependencyId();
            String dependencyName = dependency.getDependencyName();
            int requiredQuantity = dependency.getQuantity() * quantity;

            // 累加物品数量
//            totalMaterials.put(dependencyName, totalMaterials.getOrDefault(dependencyName, 0) + requiredQuantity);

            // 构建子物品数据
            Map<String, Object> materialData = new HashMap<>();
            materialData.put("name", dependencyName);
            materialData.put("quantity", requiredQuantity);

            // 递归计算该物品的依赖关系
            calculateMaterials(dependencyId, requiredQuantity, materialData);
            materials.add(materialData);
        }

        itemData.put("materials", materials);
        result.put(item.getItemName(), itemData);

    }

}